import requests
import hashlib
import base64
import hmac
import json
import time
from utils.consts import LARK_HEADERS, LARK_API_DIR, LARK_INTERVL


class LarkMsger:
    def __init__(self, title: str, note_intv: int = LARK_INTERVL) -> None:
        self.URL = None
        self.KEY = None
        # get URL and KEY from json file
        with open(LARK_API_DIR, 'r') as f:
            api = json.load(f)
            self.URL = api['URL']
            self.KEY = api['KEY']
        self.NOTE_INTERVEL = note_intv
        self.title = title

    # official API for cryptographic verification keys
    def cryptographic(self) -> tuple[str, int]:
        timestamp = int(time.time())
        string_to_sign = '{}\n{}'.format(timestamp, self.KEY)
        hmac_code = hmac.new(string_to_sign.encode(
            "utf-8"), digestmod=hashlib.sha256).digest()
        return base64.b64encode(hmac_code).decode('utf-8'), timestamp

    # wrap the api to send msg
    def send_msg(self, text: str) -> requests.Response:
        sign, timestamp = self.cryptographic()
        msg = {
            "timestamp": timestamp,
            "sign": sign,
            "msg_type": "text",
            "content": {
                "text": f"{self.title}\n\n{text}"
            },
        }
        return requests.post(self.URL, json.dumps(msg), headers=LARK_HEADERS)
